package com.applet.user.controller;

import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.applet.common.core.redis.RedisCache;
import com.applet.common.exception.parttime.partTimeException;
import com.applet.common.utils.SecurityUtils;
import com.applet.user.domain.dto.ApplyForDto;
import com.applet.user.domain.vo.ApplyForVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.applet.common.annotation.Log;
import com.applet.common.core.controller.BaseController;
import com.applet.common.core.domain.AjaxResult;
import com.applet.common.enums.BusinessType;
import com.applet.user.domain.ApplyFor;
import com.applet.user.service.IApplyForService;
import com.applet.common.utils.poi.ExcelUtil;
import com.applet.common.core.page.TableDataInfo;

/**
 * 兼职申请Controller
 *
 * @author ruoyi
 * @date 2024-08-16
 */
@Api(tags = "兼职申请")
@RestController
@RequestMapping("/user/for")
public class ApplyForController extends BaseController {
    @Autowired
    private IApplyForService applyForService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询兼职申请列表
     */
//    @PreAuthorize("@ss.hasPermi('system:for:list')")
    @ApiOperation(value = "查询兼职列表")
    @GetMapping("/list")
    public TableDataInfo list(ApplyFor applyFor) {
        startPage();
        List<ApplyFor> list = applyForService.selectApplyForList(applyFor);
        return getDataTable(list);
    }

    /**
     * 客户端查询兼职申请列表
     */
//    @PreAuthorize("@ss.hasPermi('system:for:list')")
    @ApiOperation(value = "客户端查询被申请兼职列表")
    @GetMapping("/list/client")
    public TableDataInfo clientList(ApplyForDto applyForDto) {
        startPage();
        List<ApplyForVo> list = applyForService.selectClientApplyForList(applyForDto);
        return getDataTable(list);
    }

    /**
     * 导出兼职申请列表
     */
//    @PreAuthorize("@ss.hasPermi('system:for:export')")
    @Log(title = "兼职申请", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "导出兼职列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, ApplyFor applyFor) {
        List<ApplyFor> list = applyForService.selectApplyForList(applyFor);
        ExcelUtil<ApplyFor> util = new ExcelUtil<>(ApplyFor.class);
        util.exportExcel(response, list, "兼职申请数据");
    }

    /**
     * 获取兼职申请详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:for:query')")
    @ApiOperation(value = "根据id查询兼职")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(applyForService.selectApplyForById(id));
    }

    /**
     * 新增兼职申请
     */
//    @PreAuthorize("@ss.hasPermi('system:for:add')")
    @Log(title = "兼职申请", businessType = BusinessType.INSERT)
    @ApiOperation(value = "申请兼职")
    @PostMapping
    public AjaxResult add(@RequestBody ApplyFor applyFor) {
        //将用户id和兼职表的id关联起来，存入redis中，用于断用户是否重复申请兼职
        String key = applyFor.getPublishId() + "-" + SecurityUtils.getUserId();
        try {
            if (Objects.equals(applyFor.getPublishUserId(), SecurityUtils.getUserId())) {
                return error("您不能申请自己发布的兼职哦");
            }
            if (applyFor.getIntor() == null) {
                applyFor.setIntor("暂无");
            }
            //键存在，说明申请过
            if (redisCache.hasKey(key)) {
                return error("您已经申请过该兼职，请勿重复申请");
            }
            //防止当键过期时，再次申请
            //一个新的对象接收用户Id和对应兼职的id
            ApplyFor applyForVerify = new ApplyFor();
            applyForVerify.setUserId(SecurityUtils.getUserId());
            applyForVerify.setPublishId(applyFor.getPublishId());
            applyForVerify.setStatus(0);
            //查找是否有已经申请的记录
            List<ApplyFor> list = applyForService.selectApplyForList(applyForVerify);
            if (!list.isEmpty()) {
                return error("您已经申请过该兼职，请勿重复申请");
            }
            //放到缓存中
            redisCache.setCacheObject(key, applyFor);
            //设置过期时间为20分钟
            redisCache.expire(key, 20 * 60);
            return toAjax(applyForService.insertApplyFor(applyFor));
        } catch (Exception e) {
            if (redisCache.hasKey(key)) {
                redisCache.deleteObject(key);
            }
            throw new partTimeException("兼职申请失败,请查看原因："+e.getMessage());
        }
    }

    /**
     * 修改兼职申请
     */
//    @PreAuthorize("@ss.hasPermi('system:for:edit')")
    @Log(title = "兼职申请", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改兼职申请信息")
    @PutMapping
    public AjaxResult edit(@RequestBody ApplyFor applyFor) {
        return toAjax(applyForService.updateApplyFor(applyFor));
    }

    /**
     * 批量删除兼职申请
     */
//    @PreAuthorize("@ss.hasPermi('system:for:remove')")
    @Log(title = "批量撤销兼职", businessType = BusinessType.DELETE)
    @ApiOperation(value = "批量撤销兼职")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(applyForService.deleteApplyForByIds(ids));
    }

    /**
     * 用户端撤销兼职申请
     */
    @Log(title = "撤销兼职", businessType = BusinessType.DELETE)
    @ApiOperation(value = "撤销兼职")
    @DeleteMapping("/delete")
    public AjaxResult delete(Long id,Long publishId, Long publishUserId) {
        String key = publishId + "-" + SecurityUtils.getUserId();
        //判断当前缓存是否存在要撤销的兼职，如果存在则删除
        if(redisCache.hasKey(key)){
            redisCache.deleteObject(key);
        }
        return applyForService.deleteApplyForById(id,publishUserId);
    }
}
